import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义产品store (组合式API)
export const useProductStore = defineStore('products', () => {
  // state
  const products = ref([
    { id: 1, name: '笔记本电脑', price: 5999, inventory: 10 },
    { id: 2, name: '智能手机', price: 3999, inventory: 15 },
    { id: 3, name: '耳机', price: 899, inventory: 20 }
  ])
  const nextId = ref(4)
  
  // actions
  function addProduct(product) {
    products.value.push({
      id: nextId.value++,
      ...product
    })
  }
  
  function applyDiscount(percentage) {
    products.value.forEach(product => {
      product.price = Math.round(product.price * (1 - percentage / 100))
    })
  }

  return {
    products,
    nextId,
    addProduct,
    applyDiscount
  }
})

// 定义购物车store (组合式API)
export const useCartStore = defineStore('cart', () => {
  // state
  const items = ref([])
  
  // getters
  const count = computed(() => {
    return items.value.reduce((total, item) => total + item.quantity, 0)
  })
  
  const total = computed(() => {
    return items.value.reduce((sum, item) => {
      return sum + item.price * item.quantity
    }, 0)
  })
  
  // actions
  function addToCart(product, quantity = 1) {
    const existingItem = items.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += quantity
    } else {
      items.value.push({
        id: product.id,
        name: product.name,
        price: product.price,
        quantity
      })
    }
    
    // 减少产品库存
    product.inventory -= quantity
  }
  
  function removeFromCart(itemId) {
    const index = items.value.findIndex(item => item.id === itemId)
    if (index > -1) {
      items.value.splice(index, 1)
    }
  }
  
  function clearCart() {
    items.value = []
  }

  return {
    items,
    count,
    total,
    addToCart,
    removeFromCart,
    clearCart
  }
})
